package strcy.cn.market.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import strcy.cn.market.pojo.User;
import strcy.cn.market.service.Impl.MailService;
import strcy.cn.market.service.UserService;
import strcy.cn.market.utils.BCrypt;
import strcy.cn.market.utils.Result;
import strcy.cn.market.utils.ThreadLocalUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private MailService mailService;

    /**
     * 用户注册
     * @param username 用户名
     * @param password 密码
     * @param email 邮箱
     * @param code 邮箱验证码
     * @return 返回数据
     */
    @PostMapping("/register")
    public Result register(String username, String password, String email, String code) {
        //邮箱验证码是否为空?
        if (email == null || code == null) {
            return Result.error("邮箱或验证码为空");
        }
        //邮箱唯一性？
        User u = userService.getByEmail(email);
        if (u != null) {
            return Result.error("邮箱已经存在");
        }
        //检查邮箱验证码是否正确
        boolean b = mailService.verifyCode(email, code);
        if(!b){
            return Result.error("验证码已过期");
        }
        //注册
        userService.addUser(username,password,email);
        return Result.success("注册成功");
    }

    /**
     * 登录
     * @param email 邮箱
     * @param password 密码
     * @return 返回数据
     */
    @PostMapping("/login")
    public Result login(String email, String password) {
        //查询email是否存在
        User u = userService.getByEmail(email);
        if (u == null) {
            return Result.error("不存在该邮箱");
        }
        //判断密码是否正确
        if(BCrypt.matchesPassword(password, u.getPassword())){
            //密码正确生成token
            String token = userService.login(u);
            // 构造返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("user", u);
            return Result.success(data);
        }
        return Result.error("密码错误");
    }

    //添加用户
    @PostMapping("/add")
    public Result addUser(@RequestBody User user) {
        //邮箱唯一性？
        User u = userService.getByEmail(user.getEmail());
        if (u != null) {
            return Result.error("邮箱已经存在");
        }
        userService.addUser(user);
        return Result.success();
    }
    //获取用户列表
    @GetMapping("/list")
    public Result<List<User>> getAllUser() {
        List<User> users = userService.getUserAll();
        return Result.success(users);
    }

    //根据id查询用户
    @GetMapping
    public Result<User> getUserById(Integer id) {
        User user = userService.getUserById(id);
        return Result.success(user);
    }
    /**
     * 更新用户头像
     * @param avatarUrl
     * @return
     */
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam String avatarUrl) {
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }
    //更新用户信息
    @PutMapping
    public Result updateUser(@RequestBody User user) {
        userService.update(user);
        return Result.success("操作成功");
    }
    //根据Id删除用户
    @DeleteMapping("{id}")
    public Result deleteUserById(@PathVariable("id") Integer id) {
        userService.deleteById(id);
        return Result.success();
    }
    //更改密码
    @PutMapping("/change_password")
    public Result updatePassword( String old_password, String new_password) {
        //1.oldPwd是否正确
        Map<String,Object> m = ThreadLocalUtil.get();
        String email = (String) m.get("email");
        User user = userService.getByEmail(email);

        if (!BCrypt.matchesPassword(old_password,user.getPassword())) {
            return Result.error("原密码错误");
        }
        userService.updatePwd(new_password);

        return Result.success();
    }
    //获取用户信息
    @GetMapping("/userInfo")
    public Result<User> userInfo() {
        //从token中获取用户名
        Map<String ,Object> map =  ThreadLocalUtil.get();
        String email = (String) map.get("email");
        //通过邮箱查询用户信息
        User user = userService.getByEmail(email);
        return Result.success(user);
    }
    //更新用户启用状态
    @PutMapping("/update_status")
    public Result updateUserStatus(Integer id,String status) {
        userService.updateStatusById(id,status);
        return Result.success();
    }
}
